<template>
  <div class="analysis-container">
    <header>
      <!-- 左标题 -->
      <div class="header-title">可视化分析</div>
      <!-- 右功能列表 -->
      <div class="header-option-group">
        <!-- 集团选择器 -->
        <CSelect class="mr-8" v-model="tempOrgCode" @change="getTrendQueryTaskFn">
          <el-option
            v-for="item in enterpriseArr"
            :key="item.organizationCode"
            :label="item.organizationName"
            :value="item.organizationCode"
          >
            <COption :name="item.organizationName" />
          </el-option>
        </CSelect>
        <!-- 年份选择器 -->
        <div class="mr-8"
          ><el-date-picker
            type="year"
            placeholder="请选择年份"
            v-model="tempInventoryYear"
            value-format="YYYY"
            :clearable="false"
            @change="getTrendQueryTaskFn"
        /></div>
        <el-radio-group class="header-radio mr-8" v-model="queryParams.standard">
          <el-radio-button
            v-for="(item, index) in CarbonInventoryStandardsOption"
            :key="index"
            :label="item.value"
          >
            {{ item.label }}</el-radio-button
          >
        </el-radio-group>
        <el-button type="primary" @click="exportExcel" v-btnPermission="'ECI_STATISTICS_EXPORT'">
          <CIcon type="c-xian-daochu" class="g-mr4"></CIcon>
          导出统计报表
        </el-button>
      </div>
    </header>
    <main>
      <!-- 卡片区域 -->
      <div class="card-container">
        <cardItem />
      </div>
      <!-- tabs -->
      <el-tabs v-model="activeName" class="tabs" @tab-click="handleClick">
        <el-tab-pane
          name="ECI_EMISSION_DISTRIBUTION_VIEW"
          v-if="hasBtnPermission('ECI_EMISSION_DISTRIBUTION_VIEW')"
        >
          <template #label>
            <span class="custom-tabs-label">
              <c-icon class="g-mr4" type="c-biao-fenbufenxi"></c-icon>
              <span>碳排放分布分析</span>
            </span>
          </template>
          <distributionAnalysis v-if="activeName === 'ECI_EMISSION_DISTRIBUTION_VIEW'" />
        </el-tab-pane>
        <el-tab-pane
          name="ECI_EMISSION_TREND_VIEW"
          v-if="hasBtnPermission('ECI_EMISSION_TREND_VIEW')"
        >
          <template #label>
            <span class="custom-tabs-label">
              <c-icon class="g-mr4" type="c-biao-qushifenxi"></c-icon>
              <span>碳排放趋势分析</span>
            </span>
          </template>
          <trendAnalysis v-if="activeName === 'ECI_EMISSION_TREND_VIEW'" />
        </el-tab-pane>
      </el-tabs>
    </main>
  </div>
</template>

<script lang="ts" setup>
import { CSelect } from '@/components/CSelect/index';
import { COption } from '@/components/COption/index';
import { computed, provide, reactive, ref, watch } from 'vue';
import type { TabsPaneContext } from 'element-plus';
import distributionAnalysis from './components/distributionAnalysis/index.vue';
import trendAnalysis from './components/trendAnalysis/index.vue';
import cardItem from './components/cardItem/index.vue';
import { CarbonInventoryStandardsOption, CarbonInventoryStandardsEnum } from '@/constants/enum';
import type { queryAnalysisParams } from '@/apis/eci/visualAnalysis/model/visualAnalysisModel';
import { getCurrentOrganizationList } from '@/apis/common/common';
import { useExport } from '@/hooks/useExport';
import { GetOrganizationListResult } from '@/apis/common/model/commonModel';
import { getStaticReport, getTrendQueryTask } from '@/apis/eci/visualAnalysis';
import { hasBtnPermission } from '@/directives/btnPermission';
import { useRoute } from 'vue-router';

const queryParams = reactive<queryAnalysisParams>({
  // 组织编号
  orgCode: '',
  // 盘查年份
  inventoryYear: new Date().getFullYear().toString(),
  // 核算标准
  standard: CarbonInventoryStandardsEnum.GB
});

// 集团 - 选择器
const enterpriseArr = ref<GetOrganizationListResult>([]);
const orgType = ref<'GROUP' | 'FACTORY'>('GROUP');
const tempOrgCode = ref(queryParams.orgCode);
const tempInventoryYear = ref<string>(
  queryParams.inventoryYear || new Date().getFullYear().toString()
);
const getCurrentOrganizationListFun = async () => {
  // 获取当前用户组织列表
  try {
    const res = await getCurrentOrganizationList();
    enterpriseArr.value = res;
    tempOrgCode.value = res[0].organizationCode;
    getTrendQueryTaskFn();
    console.log('getCurrentOrganizationList', res);
  } catch (error) {
    console.log(error);
  }
};
getCurrentOrganizationListFun(); // 获取当前用户组织列表

const organizationName = computed(() => {
  // select框选中的组织名称
  const currentItem = enterpriseArr.value?.find(item => {
    return queryParams.orgCode === item.organizationCode;
  });
  return currentItem?.organizationName;
});
provide('params', {
  queryParams,
  organizationName,
  orgType
});
// provide('organizationName', organizationName);
// 年份 - 选择器

// 碳盘查标准 - 选择器

// 导出 Excel 表格
const { handleExportFile } = useExport();
const exportExcel = () => {
  handleExportFile(getStaticReport, queryParams, '导出统计报表成功！');
};

const route = useRoute();
const routerName = computed(() => {
  return route.name;
});
// tabs 切换
const activeName = ref(initActiveName());

function initActiveName() {
  if (
    hasBtnPermission('ECI_EMISSION_DISTRIBUTION_VIEW') &&
    routerName.value === 'AnalysisDistribution'
  ) {
    return 'ECI_EMISSION_DISTRIBUTION_VIEW';
  } else if (
    hasBtnPermission('ECI_EMISSION_TREND_VIEW') &&
    routerName.value === 'AnalysisTendency'
  ) {
    return 'ECI_EMISSION_TREND_VIEW';
  } else {
    return hasBtnPermission('ECI_EMISSION_DISTRIBUTION_VIEW')
      ? 'ECI_EMISSION_DISTRIBUTION_VIEW'
      : hasBtnPermission('ECI_EMISSION_TREND_VIEW')
      ? 'ECI_EMISSION_TREND_VIEW'
      : '';
  }
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

/**
 * 更改组织/盘查周期后触发查询组织类型，并且更新组织code、盘查周期
 */
async function getTrendQueryTaskFn() {
  try {
    const res = await getTrendQueryTask(tempOrgCode.value, tempInventoryYear.value);
    orgType.value = res?.boundaryType === 'SELF_FILL' ? 'FACTORY' : 'GROUP';
    queryParams.orgCode = tempOrgCode.value;
    queryParams.inventoryYear = tempInventoryYear.value;
  } catch (error) {
    console.log('error', error);
  }
}
</script>

<style scoped lang="scss">
.analysis-container {
  header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px 12px 20px;
    height: 56px;
    background: #ffffff;
    border-bottom: 1px solid #f0f4f7;
    .header-title {
      font-size: 16px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 600;
      color: #0a1f33;
      line-height: 24px;
    }

    .header-option-group {
      display: flex;
      align-items: center;
      .mr-8 {
        margin-right: 8px;
      }

      :deep(.el-date-editor) {
        width: 128px;
      }

      .header-radio {
        height: 32px;
        border-radius: 3px;
        // border: 1px solid #f3f7fb;
        background: #f3f7fb;
        padding: 3px;
        :deep(.is-active .el-radio-button__inner) {
          background: #ffffff;
          border-radius: 3px;
          font-weight: 400;
          color: #0a1f33;
          &:before {
            content: '';
            width: 0;
          }
        }
        :deep(.el-radio-button__inner) {
          height: 26px;
          line-height: 22px;
          padding: 2px 12px;
          font-size: 14px;
          color: #7a8a99;
          border: none;
          position: relative;
          background: transparent;
          box-shadow: none;
          &:before {
            content: '';
            position: absolute;
            left: -1px;
            top: 7px;
            width: 1px;
            height: 12px;
            background: #e1e6eb;
          }
        }
        :deep(.is-active + .el-radio-button, .el-radio-button:first-child) {
          .el-radio-button__inner:before {
            content: '';
            width: 0;
          }
        }
      }
    }
  }
  main {
    .card-container {
      padding: 16px 20px;
      background-color: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .tabs {
      font-size: 12px;
      :deep(.el-tabs__header) {
        margin: unset;
      }
      :deep(.el-tabs__nav-wrap) {
        background: #fff;
        padding: 0 22px;
        .el-tabs__nav-scroll {
          border-top: 1px solid #f2f3f5;
          // border-bottom: 1px solid red;
          .el-tabs__item.is-active {
            color: #0a1f33;
          }
          .el-tabs__item {
            height: 48px;
            line-height: 48px;
          }
        }
        &::after {
          content: '';
          position: absolute;
          left: 0;
          bottom: 0;
          width: 100%;
          height: 1px;
          background-color: #f2f3f5;
        }
      }
      :deep(.el-tabs__content) {
        padding: 16px;
        height: calc(100vh - 50px - 56px - 144px - 48px);
        overflow: auto;
      }
    }
  }
}
</style>
